<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Itowns Examples</title>

    <link type="text/css" rel="stylesheet" href="css/example.css">
</head>

<body data-spy="scroll" data-target="nav" onload="onLoad()">

<div id="main">
    <iframe id="content" class="scroll-section" frameborder="0" height="100%"></iframe>
    <div id="view-source" class="text"></div>
</div>

<nav class="scroll-section">
    <a href="/">
        <img src="images/itowns_logo.png" width="245px"/>
    </a>
</nav>

<script type="text/javascript">
    var baseURI = document.baseURI;

    function bindIframe() {
        var navLinks = document.getElementsByClassName('nav-link');
        for (var i = 0; i < navLinks.length; i++) {
            navLinks[i].addEventListener('click', function(e) {
                e.preventDefault();
                var target = e.target.localName === 'b' ? e.target.parentNode : e.target;
                var url = target.href.replace('#', '') + '.html';
                var slug = target.hash;
                goTo(url, slug);
            });
        }

        // load page if setted
        if (document.location.hash) {
            var url = document.location.href.replace('#', '') + '.html';
            goTo(url);
        } else {
            goTo('view_3d_map.html');
        }
    }

    function goTo(url, slug) {
        if (slug) window.location.hash = slug;
        var iframe = document.getElementById('content');
        iframe.src = url.replace('index.html', '');
        iframe.focus();

        var viewSrc = '<a href="https://github.com/iTowns/itowns/blob/master/examples/';
        viewSrc += window.location.hash.substr(1) || 'view_3d_map';
        viewSrc += '.html" target="_blank">View source</a>';
        document.getElementById('view-source').innerHTML = viewSrc;
    }

    function initNavigation(list) {
        var nav = '<h2>Examples</h2>';

        for (var section in list) {
            nav += '<div class="package">';
            nav += `<h3 class="nav-section">${section}</h3>`;
            nav += '<ul>';

            for (var example in list[section]) {
                nav += '<li class="nav-item">';
                nav += `<a class="nav-link" href="#${example}">`;
                nav += `${list[section][example]}</a></li>`;
            }

            nav += '</ul></div>';
        }

        document.getElementsByTagName('nav')[0].insertAdjacentHTML('beforeend', nav);
    }

    function onLoad() {
        // Get the configuration
        fetch('./config.json').then(function _(response) {
            return response.json();
        }).then(function _(config) {
            initNavigation(config);
            bindIframe();
        });
    }
</script>
</body>
</html>
